# coding:utf-8
# 战斗技能相关逻辑

import glog, glb
import DATA_battleskill

# 技能类型 1:近身攻击 2:旋风斩 3:普通射击 4:爆炸攻击 5:线性攻击 6:多重射击
SKILL_TYPE_1 = 1
SKILL_TYPE_2 = 2
SKILL_TYPE_3 = 3
SKILL_TYPE_4 = 4
SKILL_TYPE_5 = 5
SKILL_TYPE_6 = 6


def can_attack(unit, matrix_a, matrix_b):
	return len(get_attack_targets(unit, matrix_a, matrix_b)) > 0


def get_attack_targets(unit, matrix_a, matrix_b):
	mt = None
	if unit.is_side_a(): mt = matrix_b
	else: mt = matrix_a
	
	skill_type = DATA_battleskill.data[unit.skill]['type']
	if skill_type == SKILL_TYPE_1: return get_attack_targets_type1(unit, mt)
	if skill_type == SKILL_TYPE_2: return get_attack_targets_type2(unit, mt)
	if skill_type == SKILL_TYPE_3: return get_attack_targets_type3(unit, mt)
	if skill_type == SKILL_TYPE_4: return get_attack_targets_type4(unit, mt)
	if skill_type == SKILL_TYPE_5: return get_attack_targets_type5(unit, mt)
	if skill_type == SKILL_TYPE_6: return get_attack_targets_type6(unit, mt)


# 1:近身攻击 身前1格
def get_attack_targets_type1(u, m):
	rposs = [(1,0)]
	return _get_units_by_rpos_list(rposs, u, m)


# 2:旋风斩 周围R正方形范围
def get_attack_targets_type2(u, m):
	args = DATA_battleskill.data[u.skill]
	R = args[1]

	rposs = _get_range(-R,-R, R,R)
	return _get_units_by_rpos_list(rposs, u, m)


# 3:普通射击 矩形范围
def get_attack_targets_type3(u, m):
	args = DATA_battleskill.data[u.skill]
	X = args[1]
	Y = args[2]

	rx = int(X / 2)
	ry = int(Y / 2)
	rposs = _get_range(-rx,-ry, rx,ry)
	return _get_frist_by_rpos_list(rposs, u, m)


# 4:爆炸攻击
def get_attack_targets_type4(u, m):
	args = DATA_battleskill.data[u.skill]
	X = args[2]
	Y = args[3]
	R = args[4]

	rx = int(X / 2)
	ry = int(Y / 2)
	rposs = _get_range(-rx,-ry, rx,ry)
	first_target = _get_frist_by_rpos_list(rposs, u, m)

	if first_target:
		#爆炸范围
		rposs = _get_range(-R,-R, R,R)
		targets = _get_units_by_rpos_list(rposs, first_target, m)
		return [first_target] + targets
	else:
		return []


# 5:线性攻击
def get_attack_targets_type5(u, m):
	return []


# 6:多重射击
def get_attack_targets_type5(u, m):
	return []


# 批量获取目标Matrix中的Unit
def _get_units_by_rpos_list(rposs, u, m):
	res = []
	for rpos in rposs:
		apos = _rpos_2_apos(rpos, u)
		t = m.get_unit_by_pos(apos[0], apos[1])
		if t and t.is_alive():
			res.append(t)
	return res


def _get_frist_by_rpos_list(rposs, u, m):
	for rpos in rposs:
		apos = _rpos_2_apos(rpos, u)
		t = m.get_unit_by_pos(apos[0], apos[1])
		if t and t.is_alive():
			return t
	return None


# 相对坐标转绝对坐标
# 如果为SIDE_A, X轴相加
# 如果为SIDE_B, X轴相减
# Y轴都相减
def _rpos_2_apos(p, u):
	res_x = u.x
	res_y = u.y + p[1]
	if u.is_side_a(): res_x += p[0]
	else: res_x -= p[0]
	return (res_x, res_y)


# 获取一定范围的rpos坐标
def _get_range(x, y, x1, y1):
	rposs = []
	for _x in xrange(x, x1+1):
		for _y in xrange(y, y1+1):
			rposs.append((_x, _y))
